
# include "dfxTimer_Win32.h"

namespace DFX
{
    Timer_Win32::Timer_Win32()
        : mSecsPerCount(0.0), 
        mDeltaTime(0.0), 
        mBaseTime(0), 
        mStopTime(0),
        mPausedTime(0), 
        mPrevTime(0), 
        mCurrTime(0), 
        mStopped(false)
    {
        Int64 countsPerSec;

        QueryPerformanceFrequency((LARGE_INTEGER*)&countsPerSec);
        mSecsPerCount = 1.0 / (Float64)countsPerSec;
    }

    Timer_Win32::~Timer_Win32()
    {
    }

    Float32	Timer_Win32::GetGameTime() const
    {
        if (mStopped)
            return (Float32)((mStopTime - mBaseTime) * mSecsPerCount);
        else
            return (Float32)(((mCurrTime - mPausedTime) - mBaseTime) * mSecsPerCount);
    }

    Float32 Timer_Win32::GetDeltaTime() const
    {
        return (Float32)mDeltaTime;
    }

    void Timer_Win32::Reset()
    {
        Int64 currTime;
        QueryPerformanceCounter((LARGE_INTEGER*)&currTime);

        mBaseTime = currTime;
        mPrevTime = currTime;
        mStopTime = 0;
        mStopped = false;
    }

    void Timer_Win32::Start()
    {
        Int64 startTime;
        QueryPerformanceCounter((LARGE_INTEGER*)&startTime);

        if (mStopped)
        {
            mPausedTime += (startTime - mStopTime);

            mPrevTime = startTime;
            mStopTime = 0;
            mStopped = false;
        }
    }

    void Timer_Win32::Stop()
    {
        if (!mStopped)
        {
            Int64 currTime;
            QueryPerformanceCounter((LARGE_INTEGER*)&currTime);

            mStopTime = currTime;
            mStopped = true;
        }
    }

    void Timer_Win32::Tick()
    {
        if (!mStopped)
        {
            Int64 currTime;
            QueryPerformanceCounter((LARGE_INTEGER*)&currTime);

            mCurrTime = currTime;
            mDeltaTime = (mCurrTime - mPrevTime) * mSecsPerCount;
            mPrevTime = mCurrTime;

            if (mDeltaTime < 0.0)
                mDeltaTime = 0.0;
        }
    }
}